package com.ng.common.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author cb
 * @Description TODO
 * @date 2023/4/8
 */
public class FileuploadUtils {

    public static HttpServletResponse download(String absolutePath, HttpServletResponse response,String filename) {
        InputStream fis = null;
        OutputStream toClient = null;
        try {
            // path是指欲下载的文件的路径。
            File file = new File(absolutePath);
            if(!file.exists()){
                response.setContentType("text/html; charset=UTF-8"); //转码
                PrintWriter out = response.getWriter();
                out.flush();
                out.println("<script defer='defer' type='text/javascript'>");
                out.println("alert('文件不存在或已经被删除！请联系管理员');");

                out.println("</script>");

                return response;
            }
            try {
                // 以流的形式下载文件。
                fis = new BufferedInputStream(new FileInputStream(absolutePath));
            } catch (FileNotFoundException e) {//文件找不到,直接返回
                response.setContentType("text/html; charset=UTF-8"); //转码
                PrintWriter out = response.getWriter();
                out.flush();
                out.println("<script defer='defer' type='text/javascript'>");
                out.println("alert('文件不存在或已经被删除！请联系管理员');");

                out.println("</script>");

                return response;
            }
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            // response.reset();  //不注释掉会有 org.apache.catalina.connector.ClientAbortException: java.io.IOException: 你的主机中的软件中止了一个已建立的连接
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
            response.addHeader("Content-Length", "" + file.length());
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (toClient != null) {
                    toClient.close();
                }
                if (fis != null) {
                    toClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}
